<!-- src/views/warehousing/entry/entryAOU.vue -->
<script setup>
import { getWarehouseListApi } from '@/api/warehouse';
import { addWarehousingEntryApi, updateWarehousingEntryApi } from '@/api/warehousingEntry';
import { ElMessage } from 'element-plus';
import { getCurrentInstance, onMounted, ref } from 'vue';
import SkuSelector from './SkuSelector.vue';
import { getUserListApi } from '@/api/user';

const instance = getCurrentInstance()
const ruleFormRef = ref(null)
const dialogFormVisible = ref(false)
const title = ref('')
const warehouseList = ref([])
const skuSelectorVisible = ref(false) // SKU选择弹框可见性
const selectedSkus = ref([]) // 已选择的SKU列表
const userList = ref([]) // 货主列表

const entryForm = ref({
  id: '',
  consignorId: '', // 货主ID
  batchNumber: '',
  predictedArrivalTime: '',
  warehouseId: '', // 仓库ID
  items: [] // 商品信息集合
})

const reset = () => {
  entryForm.value = {
    id: '',
    consignorId: '',
    batchNumber: '',
    predictedArrivalTime: '',
    warehouseId: '',
    items: []
  }
  selectedSkus.value = [] // 重置已选择的SKU
}

// 设置SKU数据的方法
const setSkuData = (data) => {
  selectedSkus.value = data.map(item => ({
    id: item.id,
    code: item.code,
    title: item.title,
    supplierId: item.supplierId,
    supplierName: item.supplierName
  }))
  
  entryForm.value.items = data.map(item => ({
    id: item.id,
    code: item.code,
    title: item.title,
    supplierId: item.supplierId
  }))
}

// 打开SKU选择弹框
const openSkuSelector = () => {
  skuSelectorVisible.value = true
}

// 确认选择SKU
const handleSkuConfirm = (skus) => {
  selectedSkus.value = skus
  // 同时更新表单中的items字段，将skuId改为id，supplierName改为supplierId
  entryForm.value.items = skus.map(sku => ({
    id: sku.id,              // 将skuId改为id
    code: sku.code,
    title: sku.title,
    supplierId: sku.supplierId  // 保存supplierId而不是supplierName
  }))
}

const save = async () => {
  if (!ruleFormRef) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let res = null
      if (entryForm.value.id) {
        res = await updateWarehousingEntryApi(entryForm.value)
      } else {
        res = await addWarehousingEntryApi(entryForm.value)
      }
      if (res.code == 1) {
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        instance.emit('refresh')
      } else {
        ElMessage.error('操作失败')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const rules = ref({
  batchNumber: [
    { required: true, message: '批次号不能为空', trigger: 'blur' }
  ],
  predictedArrivalTime: [
    { required: true, message: '预测到达时间不能为空', trigger: 'blur' }
  ],
  consignorId: [
    { required: true, message: '货主不能为空', trigger: 'blur' }
  ],
  warehouseId: [
    { required: true, message: '仓库不能为空', trigger: 'blur' }
  ]
})

const getWarehouseList =async () =>{
  const res = await getWarehouseListApi()
  warehouseList.value = res.data
}

// 获取货主列表
const getUserList = async () => {
  const res = await getUserListApi()
  userList.value = res.data
}

defineExpose({
  dialogFormVisible,
  title,
  entryForm,
  reset,
  setSkuData // 暴露设置SKU数据的方法
})

onMounted(() => {
  getWarehouseList()
  getUserList()
})
</script>

<template>
  <el-dialog 
    v-model="dialogFormVisible" 
    :title="title"
    width="600px"
    top="5vh"
  >
    <el-form 
      :model="entryForm" 
      :rules="rules" 
      ref="ruleFormRef" 
      label-width="120px"
      style="padding: 20px 20px 0;"
    >
      <el-form-item label="批次号" prop="batchNumber">
        <el-input 
          v-model="entryForm.batchNumber" 
          placeholder="请输入批次号"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="预计送达时间" prop="predictedArrivalTime">
        <el-date-picker 
          v-model="entryForm.predictedArrivalTime" 
          type="datetime" 
          placeholder="请选择日期时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%;"
        />
      </el-form-item>
      
      <el-form-item label="货主" prop="consignorId">
        <el-select 
          v-model="entryForm.consignorId" 
          placeholder="请选择货主"
          clearable
          style="width: 100%;"
        >
          <el-option 
            v-for="item in userList" 
            :key="item.id" 
            :label="item.name" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="仓库" prop="warehouseId">
        <el-select 
          v-model="entryForm.warehouseId" 
          placeholder="请选择仓库"
          clearable
          style="width: 100%;"
        >
          <el-option 
            v-for="item in warehouseList" 
            :key="item.id" 
            :label="item.name" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>
      
      <!-- SKU选择区域 -->
      <el-form-item label="商品信息">
        <el-button 
          type="primary" 
          icon="Plus"
          @click="openSkuSelector"
        >
          选择商品
        </el-button>
      </el-form-item>
      
      <!-- 已选择的商品信息展示 -->
      <el-form-item v-if="selectedSkus.length > 0" label="">
        <div class="selected-skus-container">
          <div class="table-header">
            <span>已选择 {{ selectedSkus.length }} 项商品</span>
          </div>
          <el-table 
            :data="selectedSkus" 
            size="small" 
            max-height="250"
            stripe
            border
          >
            <el-table-column prop="code" label="商品编码" min-width="100" />
            <el-table-column prop="title" label="商品名称" min-width="120" />
            <el-table-column prop="supplierName" label="供应商" min-width="100" />
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false" icon="Close">
          取消
        </el-button>
        <el-button type="primary" @click="save" icon="Check">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  
  <!-- SKU选择弹框 -->
  <SkuSelector 
    v-model:visible="skuSelectorVisible" 
    @confirm="handleSkuConfirm" 
  />
</template>

<style scoped>
.selected-skus-container {
  width: 100%;
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 20px;
}

.dialog-footer .el-button {
  padding: 8px 20px;
}
</style>